package lib

import (
	"encoding/json"
	uuid "github.com/satori/go.uuid"
	"hello/conf"
	"hello/lib/redisLib"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)
type AccessTokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn int `json:"expires_in"`
}

func GenerateUUID() string {
	var err error
	return uuid.Must(uuid.NewV4(), err).String()
}

func AcquireAccessToken() (string, error){
	url := strings.Replace(conf.AccessTokenUrl, "APPID", conf.AppId, 1)
	url = strings.Replace(url, "SECRET", conf.AppSecret, 1)
	//fmt.Println(url)
	resp, e := http.Get(url)
	if e != nil {
		log.Printf("acquire access token error :%s", e)
		return "", e
	}
	respByte, e := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(respByte))
	if e != nil {
		log.Printf("get response body error : %s", e)
		return "", e
	}
	var accToken AccessTokenResponse
	e = json.Unmarshal(respByte, &accToken)
	if e != nil {
		log.Printf("unmarshal access token response error :%s", e)
		return "", e
	}
	token := accToken.AccessToken
	return token, nil
}

func CreateUserID() (int64, error) {
	num, _ := redisLib.Incr(redisLib.Session, redisLib.UserID)
	idnum := int64(1000000) + num
	return idnum, nil
}
//Byte to string
func B2S(bs []uint8) string {
	var ba []byte
	for _, b := range bs {
		ba = append(ba, b)
	}
	return string(ba)
}

func SaveAccessToken() {
	token, err := AcquireAccessToken()
	if err != nil {
		log.Printf("get access token from wechat error: %s", err.Error())
	}
	err = redisLib.Set(redisLib.DB0, redisLib.AccessToken, token, redisLib.TokenExpireTime)
	if err != nil {
		log.Printf("set redis key error : %s", err.Error())
	}
}

func GetAccessToken() string {
	token, err := redisLib.Get(redisLib.DB0, redisLib.AccessToken)
	if err != nil {
		log.Printf("get redis data error: %s", err.Error())
		return ""
	}
	//log.Print("TOKEN"+token+"TOKEN")
	if token == "" {
		SaveAccessToken()
	}
	token, err = redisLib.Get(redisLib.DB0, redisLib.AccessToken)
	return token
}